#!/usr/bin/php -q
<?php
// Include Creovel Base.
require_once('base');

if (!is_file($args[0]) && !is_dir($args[0])) return;

/**
 * Build file lists.
 */

$files = array();
$filter = '/_test.php$/';
$recursive = true;

foreach ($args as $path) {
	if (is_dir($path)) {
		// get test files
		$files = array_merge($files, dir_to_array($path, array('recursive' => true, 'filter' => $filter)));
	} elseif (is_file($path)) {
		$files[] = $path;
	}

}

/**
 * Foreach file run test.
 */

$ok = 0;
$tests = 0;
$assertions = 0;
$failures = 0;
$show_title = false;

if (count($files)) foreach ($files as $file) {
	if (file_exists($file)) {
		
		// run phpunit
		exec("phpunit {$file}", $output, $return_var);
		
		if (!$show_title) {
			echo "Creovel Test: {$output[0]}\n\n";
			$show_title = true;
		}
		
		$result = array_pop($output);
		
		if (starts_with('OK ', $result)) {
			$ok++;
			if (preg_match('/([0-9]+) test/', $result, $match1)) {
				$tests += $match1[1];
			}

			if (preg_match('/([0-9]+) assertion/', $result, $match2)) {
				$assertions += $match2[1];
			}
		} else {
			if (preg_match('/Tests: ([0-9]+)/', $result, $match1)) {
				$tests += $match1[1];
			}

			if (preg_match('/Assertions: ([0-9]+)/', $result, $match2)) {
				$assertions += $match2[1];
			}

			if (preg_match('/Failures: ([0-9]+)/', $result, $match3)) {
				$failures += $match3[1];
			}
		}
		
		echo "{$result} -> {$file}\n";
		
		if (!starts_with('OK ', $result)) {
			
			foreach ($output as $k => $line) {
				if ($k < 2) continue;
				echo "---- " . $line . "\n";
			}
			
		}
		
	} else {
		echo "File not found! -> {$file}\n";
	}
}

$total = count($files);

echo "\nResults: {$ok} of {$total} Files \"OK\" (tests: {$tests}, assertions: {$assertions}, failures: {$failures})\n";